package com.taotao.openapi2.config;

import com.taotao.openapi2.common.BusinessException;
import com.taotao.openapi2.common.RespData;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.exception.StatusException;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.validation.ValidatorException;

@Slf4j
@Component(index = 0) //index 为顺序位（不加，则默认为0）
public class ExceptionFilter implements Filter {
    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try {
            chain.doFilter(ctx);
        } catch (BusinessException e) {
            ctx.render(RespData.failedResp(e.getMessage()));
        } catch (ValidatorException e) {
            ctx.render(RespData.failedResp(e.getMessage())); //e.getResult().getDescription()
        } catch (StatusException e) {
            if (e.getCode() == 404) {
                ctx.status(e.getCode());
            } else {
                ctx.render(RespData.failedResp(e.getMessage()));
            }
        } catch (Throwable e) {
            log.error("",e);
            ctx.render(RespData.failedResp("服务端运行出错"));
        }
    }
} 